package other.one.advance;

import other.one.RoomService;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 进阶版
 */
public class RoomServiceImplAdvance implements RoomService {
    private final ConcurrentMap<String, Set<String>> roomCache = new ConcurrentHashMap<>();


    // 用于解决进入房间和退出房间先后不确定问题
    private final ConcurrentMap<String, Integer> userIdList = new ConcurrentHashMap<>();


    @Override
    public synchronized void joinRoom(String userId, String roomId) throws RuntimeException {
        // 特殊情况判断
        if (roomId == null | userId == null) {
            return;
        }
        // 设置默认值为0
        userIdList.putIfAbsent(userId, 0);
        // 如果该用户还没有退出房间，不能再次加入房间
        if (userIdList.get(userId) == 1) {
            return;
        }
        // 用户加入房间时，加1
        userIdList.put(userId, userIdList.get(userId) + 1);
        roomCache.computeIfAbsent(roomId, t -> new HashSet<>());
        if (userIdList.get(userId) == 1) {
            roomCache.get(roomId).add(userId);
        }

    }

    @Override
    public synchronized void leaveRoom(String userId, String roomId) throws RuntimeException {
        // 特殊情况判断
        if (roomId == null | userId == null) {
            return;
        }
        userIdList.putIfAbsent(userId, 0);
        if (userIdList.get(userId) == -1) {
            return;
        }
        userIdList.put(userId, userIdList.get(userId) - 1);
        if (userIdList.get(userId) == 0) {
            Set<String> userSet = roomCache.get(roomId);
            if (userSet == null) {
                return;
            }
            userSet.remove(userId);
        }
    }

    @Override
    public Collection<String> queryUser(String roomId) throws RuntimeException {
        Set<String> userId = roomCache.get(roomId);
        return null == userId ? new HashSet<>() : userId;
    }
}